/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BASearchResultsTableViewController.m
//  redia-bapps-ios
//
//  Created by Mads Darø Kristensen on 10/9/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BASearchResultsTableViewController.h"
#import "BASearchResultCell.h"
#import "BARecord.h"
#import "BALoadingIndicatorCell.h"
#import "BACollection.h"
#import "BARecord.h"
#import "InfoGalleriImageUrlUtils.h"
#import "LazyLoadManager.h"
#import "BAMaterialViewController.h"
#import "BACoverUrlAndAvailabilityMemoryCache.h"
#import "BARootViewController.h"

@interface BASearchResultsTableViewController ()

@property (strong, nonatomic) NSMutableArray *records;
//@property (strong, nonatomic) NSMutableDictionary *coverUrls;
//@property (nonatomic, strong) NSMutableDictionary* availabilityRecords;

@end

@implementation BASearchResultsTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];

    self.records = [NSMutableArray new];
    if (RD_IS_IPAD) {
        [self.tableView registerNib:[UINib nibWithNibName:@"BASearchResultCell_iPad" bundle:nil] forCellReuseIdentifier:@"SearchResultCell"];
    } else {
        [self.tableView registerNib:[UINib nibWithNibName:@"BASearchResultCell_iPhone" bundle:nil] forCellReuseIdentifier:@"SearchResultCell"];
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"BALoadingIndicatorCell" bundle:nil] forCellReuseIdentifier:@"LoadingIndicatorCell"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableWithNotification:) name:BA_COVER_URL_CACHE_IMAGE_LOADED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNewCoverUrls:) name:BA_COVER_URL_CACHE_COVER_URLS_ARRIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableWithNotification:) name:BA_AVAILAIBILITY_CACHE_AVAILABILITIES_ARRIVED object:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_COVER_URL_CACHE_IMAGE_LOADED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_COVER_URL_CACHE_COVER_URLS_ARRIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_AVAILAIBILITY_CACHE_AVAILABILITIES_ARRIVED object:nil];

}

- (void)appendRecords:(NSArray *)records
{
    [self.records addObjectsFromArray:records];
    [self.tableView reloadData];
    
    // Start fetching coverURLs.
    NSMutableArray *identifiers = [NSMutableArray new];
    for (BARecord *record in records) {
        [identifiers addObject:record.identifier];
    }
    [BARPCManager getCoverUrlsAsyncFromView:self
                            coverUrlQueries:identifiers
                                resultBlock:^(NSDictionary* result) {
                                    BACoverUrlAndAvailabilityMemoryCache* cache = [BACoverUrlAndAvailabilityMemoryCache instance];
                                    [cache appendCoverUrls:result];
                                    [self.tableView reloadData];
                                }
                                 errorBlock:^(int errorCode, NSString *errorMessage) {
                                     DLog(@"error fetching coverurls %d %@",errorCode, errorMessage);
                                 }];
    
    // Start fetching availability info.
    [BARPCManager getAvailabilityAsyncFromView:self
                                   identifiers:identifiers
                            includeHoldingInfo:NO
                                   resultBlock:^(NSDictionary *result) {
                                       BACoverUrlAndAvailabilityMemoryCache* cache = [BACoverUrlAndAvailabilityMemoryCache instance];
                                       [cache appendAvailabilityRecords:result];
                                       [self.tableView reloadData];
                                   }
                                    errorBlock:^(int errorCode, NSString *errorMessage) {
                                        DLog(@"error fetching availability %d %@",errorCode, errorMessage);
                                    }];
}

- (void)appendSearchResult:(BASearchResult *)searchResult
{
    NSMutableArray *records = [NSMutableArray new];
    for (BACollection *collection in searchResult.data) {
        [records addObjectsFromArray:collection.records];
    }
    [self appendRecords:records];
}

-(void)appendCoverUrls:(NSDictionary *)coverUrls
{
    [[BACoverUrlAndAvailabilityMemoryCache instance] appendCoverUrls:coverUrls];
    
    [self.tableView reloadData];
}

-(void)reloadTableWithNotification:(id)sender
{
    [self.tableView reloadData];
}

-(void)handleNewCoverUrls:(id)sender
{
    NSArray* visibleCells = [self.tableView visibleCells];
    NSMutableArray* visibleIdentifiers = [NSMutableArray new];
    
    for (BASearchResultCell* cell in visibleCells) {
        if ([cell isKindOfClass:[BASearchResultCell class]]) {
            if (cell.record && [cell.record.identifier length]>0) {
                [visibleIdentifiers addObject:cell.record.identifier];
            }
        }
    }
    [[BACoverUrlAndAvailabilityMemoryCache instance] fetchCoverImagesForIdentifiers:visibleIdentifiers];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self.records count] > 0) {
        if (self.dataSource && [self.dataSource hasMoreResults]) {
            return 2;
        }
        return 1;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return [self.records count];
    }
    else {
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        return 44;
    }
    if (RD_IS_IPAD) {
        return BA_SEARCH_RESULT_CELL_DEFAULT_HEIGHT_IPAD;

    } else {
        return BA_SEARCH_RESULT_CELL_DEFAULT_HEIGHT_IPHONE;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        BASearchResultCell* cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell" forIndexPath:indexPath];
        BARecord* record = [self.records objectAtIndex:indexPath.row];
        [cell setRecord:record];
        
        
        BACoverUrlAndAvailabilityMemoryCache* cache = [BACoverUrlAndAvailabilityMemoryCache instance];
        
        BAAvailability* availabilityInfo = [cache getAvailabilityForIdentifier:record.identifier];
        if (availabilityInfo) {
            [cell setAvailability:availabilityInfo];
        }
       
        [[BACoverUrlAndAvailabilityMemoryCache instance] fetchCoverImagesForIdentifiers:@[record.identifier]];
        //DEP.: now done through cache: [cell fetchCoverImage];
        
        /* old code
        BACoverUrl* coverurl_info = [self.coverUrls objectForKey:record.identifier];
        
        if (coverurl_info) {
            if (coverurl_info.searchResultCellSizedImage) {
                [cell setCoverImage:coverurl_info.searchResultCellSizedImage];
            } else {
                if (!coverurl_info.isFetchingImage) {
                    coverurl_info.isFetchingImage=TRUE;
                    NSString* resize_url = [InfoGalleriImageUrlUtils getResizedImageUrl:coverurl_info.url toWidth:50 toHeight:75 usingQuality:7 withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX outputFormat:@"jpeg" doubleUpForRetina:YES];
                    [cell loadCoverFromUrl:resize_url withBACoverUrl:coverurl_info];
                }
            }
        }
        */
        
        return cell;
    }
    else{
        BALoadingIndicatorCell* cell = [tableView dequeueReusableCellWithIdentifier:@"LoadingIndicatorCell" forIndexPath:indexPath];
        [cell.loadingIndicator startAnimating];
        if ([self.dataSource hasMoreResults]) {
            [self.dataSource loadMoreResults];
        }
        return cell;
    }
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController<BAMaterialViewControllerProtocol>* mvc = [[BARootViewController instance] createMaterialViewController]; // [BAMaterialViewController new];
    [self.navigationController pushViewController:mvc animated:YES];
    BARecord* rec = [self.records objectAtIndex:indexPath.row];
    
    BACoverUrlAndAvailabilityMemoryCache* cache = [BACoverUrlAndAvailabilityMemoryCache instance];
    
    BACoverUrl* cu_object = [cache getCoverUrlForIdentifier:rec.identifier]; //was: [self.coverUrls objectForKey:rec.identifier];
    BAAvailability* availability = [cache getAvailabilityForIdentifier:rec.identifier]; //was:  [self.availabilityRecords objectForKey:rec.identifier];
    UIImage* currentImage = [cache getSearchResultCellSizedCoverImageForIdentifier:rec.identifier];

    [mvc showRecord:rec withCoverUrl:cu_object.url currentImage:currentImage availability:availability];
}

@end
